package com.iplant.mes.serviceImpl.thread;

import com.iplant.aps.serviceImpl.APSServiceImpl;
import com.iplant.base.utils.general.CalendarTool;
import com.iplant.base.utils.tasker.TaskTimerUtils;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.mes.serviceImpl.AndonServiceImpl;
import com.iplant.mes.serviceImpl.MESServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;

@Component
public class MESThread implements DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(MESThread.class);

    @PostConstruct
    public void init() {
        Run();
    }

    private void Run() {
        new Thread(() -> {
            try {
                Thread.sleep(5000);

                //每晚3点执行一次
                Calendar wSTime = Calendar.getInstance();
                wSTime.set(wSTime.get(Calendar.YEAR), wSTime.get(Calendar.MONTH), wSTime.get(Calendar.DATE), 3, 0, 0);

                Calendar wETime = Calendar.getInstance();
                wETime.set(wSTime.get(Calendar.YEAR), wSTime.get(Calendar.MONTH), wSTime.get(Calendar.DATE), 3, 59,
                        59);

                //自动关闭过期的派工单
//                TaskTimerUtils.AddTask(() ->
//                                MESServiceImpl.getInstance().SFC_AutoCloseTaskSelfList(BMSEmployee.SysAdmin), wSTime,
//                        wETime,
//                        60000, -1);

                //循环设备列表
                //设备采集自检  加参数 设备ID
                TaskTimerUtils.AddTask(() ->
                                MESServiceImpl.getInstance().MES_AutoProcessToSelf(BMSEmployee.SysAdmin),
                        CalendarTool.getDate(),
                        CalendarTool.getDateMaxMill(), 5000, -1);

                //自动补齐日计划
                APSServiceImpl.getInstance().APS_AutoCompleteDailyPlan(BMSEmployee.SysAdmin);

                //生产状态看板数据定时更新
                TaskTimerUtils.AddTask(() -> AndonServiceImpl.getInstance().Andon_UpdateProductStatusData(BMSEmployee.SysAdmin),
                        60000);

                //工序计划历史完成数维护
                TaskTimerUtils.AddTask(() ->
                                MESServiceImpl.getInstance().MES_AutoUpdateHisActNum(BMSEmployee.SysAdmin),
                        wSTime,
                        wETime, 60000, -1);
            } catch (Exception ex) {
                logger.error("ApplicationThread", ex);
            }
        }).start();
    }

    @Override
    public void destroy() {
        TaskTimerUtils.destroy();
    }
}
